package com.worklikedance.priceonline;

import java.lang.ref.WeakReference;
import java.util.ArrayList;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Fragment;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Parcelable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.view.ViewGroup.LayoutParams;
import android.widget.Toast;

import com.google.ads.AdRequest.ErrorCode;
import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import com.worklikedance.customcontrols.TabButton;
import com.worklikedance.util.Utilities;
//import com.google.ads.AdView;

@SuppressLint("NewApi") public class MainActivity extends Activity {
	
	private static final int NUMBER_OF_TABS = 2;
	
//	public static ThreadStatus mFetchThreadStatus = ThreadStatus.Run;
	public static Thread mFetchDataThread = null;
	
	protected ViewPager mViewPager = null;
	private ViewPagerAdater mAdapter = new ViewPagerAdater();
	private ArrayList<TabButton> mTabButtons = new ArrayList<TabButton>();
	private ArrayList<View> mViews = new ArrayList<View>();
	private int mSelectedTab = 0;
	public View mAdFragmentView = null;
	private static WeakReference<MainActivity> sMainActivity = null;
	
	public static MainActivity getInstance() {
		if (sMainActivity == null) {
			return null;
		}
		
		return sMainActivity.get();
	}
	
	/** The view to show the ad. */
//	private AdView adView;
	
	@Override
	protected void onDestroy() {	
		super.onDestroy();
		
		sMainActivity = null;
	}
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		sMainActivity = new WeakReference<MainActivity>(this);
		
		initializeTabButtons();
		
		if (Utilities.isTablet(this)) {
			mTabButtons.get(0).setEnabled(false);
			mTabButtons.get(1).setEnabled(false);
			
			mViews.add( findViewById(R.id.goldView) );
			mViews.add( findViewById(R.id.rateView) );
		}
		else {
			initializeViewPager();
			highlightTabButtonAtIndex(mSelectedTab);
		}
		
		mAdFragmentView = findViewById(R.id.adFragment);
	}
	
	
	
	private void triggerFetchData() {
		for (int i = 0; i < mViews.size(); i ++) {
			RelativeLayoutEx view = (RelativeLayoutEx) mViews.get(i);
			
			if (view == null) {
				continue;
			}
			
			view.fetchData(false);
		}
	}
	
	public void dismissPopup() {
		if (mViews != null && mViews.size() > 0) {
			for (View view : mViews) {
				RelativeLayoutEx viewEx = (RelativeLayoutEx)view;
				viewEx.dismissPopup();
			}
			 
		}
	}
	
//	public static synchronized void changeThreadStatus(ThreadStatus threadStatus) {
//		mFetchThreadStatus = threadStatus;
//	}
	
	@Override
	protected void onResume() {
		super.onResume();

		// Start thread
//		changeThreadStatus(ThreadStatus.Run);
//		
//		if (mFetchDataThread == null) {
//			createAutoFetchDataThreadProc();
//		}
		
		triggerFetchData();
	}
	
	@Override
	protected void onPause() {
		super.onPause();
		
//		if ( isChangingConfigurations() == false ) 
		{
			// Pause thread
//			changeThreadStatus(ThreadStatus.Stop);
//			mFetchDataThread = null;
		}
	}
	
//	private void createAutoFetchDataThreadProc() {
//		mFetchDataThread = new Thread(new Runnable() {
//			@Override
//			public void run() {
//				while (mFetchThreadStatus != ThreadStatus.Stop) {
//					if (mFetchThreadStatus == ThreadStatus.Pause) {
//						try {
//							Thread.sleep(1000);
//						} catch (InterruptedException e) {
//							e.printStackTrace();
//						}
//						
//						Log.d("FetchingThread", "Pausing");
//					}
//					else {
//						try {
//							Thread.sleep(Constant.AUTO_FETCH_DATA_INTERVAL);
//						} 
//						catch (InterruptedException e) {
//							e.printStackTrace();
//						}
//
//						runOnUiThread(new Runnable() {
//							@Override
//							public void run() {
//								triggerFetchData();
//							}
//						});
//						
//						Log.d("FetchingThread", "Running");
//					}
//				}
//			}
//		});
//		
//		mFetchDataThread.start();
//	}
	
	private void initializeTabButtons() {
		TabButton goldPriceTabButton = (TabButton)findViewById(R.id.goldViewTabButton);
		TabButton exchangeRateTabButton= (TabButton)findViewById(R.id.exchangeRateTabButton);
		
		goldPriceTabButton.setTitleSource(getString(R.string.gold_title), R.drawable.button_gold_price_icon, getString(R.string.sjc_source));
		exchangeRateTabButton.setTitleSource(getString(R.string.rate_title), R.drawable.button_rate_icon, getString(R.string.vietcomank_source));
		
		mTabButtons.add(goldPriceTabButton);
		mTabButtons.add(exchangeRateTabButton);
	}
	
	private void initializeViewPager() {
		LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		
		View priceView = inflater.inflate(R.layout.price, null);
		View rateView = inflater.inflate(R.layout.rate, null);
		
		mViews.add(priceView);
		mViews.add(rateView);
		
		mViewPager = (ViewPager)findViewById(R.id.viewPager);
		mViewPager.setOffscreenPageLimit(2);
		mViewPager.setAdapter(mAdapter);		
		mAdapter.notifyDataSetChanged();
		mViewPager.setOnPageChangeListener(new OnPageChangeListener() {
			
			@Override
			public void onPageSelected(int arg0) {
				highlightTabButtonAtIndex(arg0);
			}
			
			@Override
			public void onPageScrolled(int arg0, float arg1, int arg2) {
			}
			
			@Override
			public void onPageScrollStateChanged(int arg0) {				
			}
		});
	}
	
	protected void highlightTabButtonAtIndex(int index) {
		if (index >= NUMBER_OF_TABS) {
			return;
		}
		
		mSelectedTab = index;
		mViewPager.setCurrentItem(index,true);
		
		TabButton widgetButton = mTabButtons.get(index);				
		
		for (TabButton button : mTabButtons) {
			button.setEnabled(true);
		}
		
		widgetButton.setEnabled(false);		
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}
	
	@Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case R.id.menu_danh_gia:
            processDanhGia();
            return true;
            
        case R.id.menu_gop_y:
        	processGopY();
        	return true;
        	
        default:
            return super.onOptionsItemSelected(item);
        }
    }
		
	private void processDanhGia() {
		final Uri uri = Uri.parse("market://details?id=" + getApplicationContext().getPackageName());
		final Intent rateAppIntent = new Intent(Intent.ACTION_VIEW, uri);

		if (getPackageManager().queryIntentActivities(rateAppIntent, 0).size() > 0) {
		    startActivity(rateAppIntent);
		}
		else {		    
			Toast.makeText(this, getString(R.string.pls_try_again), Toast.LENGTH_SHORT).show();
		}
	}
	
	private void processGopY() {
		Intent i = new Intent(Intent.ACTION_SEND);
		
		i.setType("message/rfc822");
		i.putExtra(Intent.EXTRA_EMAIL  , new String[]{"utilvietapps@gmail.com"});
		i.putExtra(Intent.EXTRA_SUBJECT, getString(R.string.subject_gop_y));
		i.putExtra(Intent.EXTRA_TEXT   , "");
		
		try {
		    startActivity(Intent.createChooser(i, "Send mail..."));
		} 
		catch (android.content.ActivityNotFoundException ex) {
		    Toast.makeText(this, "There are no email clients installed.", Toast.LENGTH_SHORT).show();
		}
	}

	public void onClickGoldPrice(View v) {
		highlightTabButtonAtIndex(0);
	}
	
	public void onClickRate(View v) {
		highlightTabButtonAtIndex(1);
	}
	
	protected class ViewPagerAdater extends PagerAdapter {

		@Override
		public int getCount() {
			return mViews.size();
		}
		
		/**
		 * Create the page for the given position.  The adapter is responsible
		 * for adding the view to the container given here, although it only
		 * must ensure this is done by the time it returns from
		 * {@link #finishUpdate(android.view.ViewGroup)}.
		 *
		 * @param collection The containing View in which the page will be shown.
		 * @param position The page position to be instantiated.
		 * @return Returns an Object representing the new page.  This does not
		 * need to be a View, but can be some other container of the page.
		 */
		@Override
		public Object instantiateItem(ViewGroup collection, int position) {
			View view = mViews.get(position);

			view.setLayoutParams(new ViewGroup.LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.MATCH_PARENT));			
			collection.addView(view);									
			
			return view;			
		}

		/**
		 * Remove a page for the given position.  The adapter is responsible
		 * for removing the view from its container, although it only must ensure
		 * this is done by the time it returns from {@link #finishUpdate(android.view.ViewGroup)}.
		 *
		 * @param collection The containing View from which the page will be removed.
		 * @param position The page position to be removed.
		 * @param view The same object that was returned by
		 * {@link #instantiateItem(android.view.View, int)}.
		 */
		@Override
		public void destroyItem(ViewGroup collection, int position, Object view) {
			collection.removeView((View) view);
		}


		/**
		 * Determines whether a page View is associated with a specific key object
		 * as returned by instantiateItem(ViewGroup, int). This method is required
		 * for a PagerAdapter to function properly.
		 * @param view Page View to check for association with object
		 * @param object Object to check for association with view
		 * @return
		 */
		@Override
		public boolean isViewFromObject(View view, Object object) {
			return (view==object);
		}				

		/**
		 * Called when the a change in the shown pages has been completed.  At this
		 * point you must ensure that all of the pages have actually been added or
		 * removed from the container as appropriate.
		 * @param arg0 The containing View which is displaying this adapter's
		 * page views.
		 */
		@Override
		public void finishUpdate(ViewGroup arg0) {}		

		@Override
		public void restoreState(Parcelable arg0, ClassLoader arg1) {}

		@Override
		public Parcelable saveState() {
			return null;
		}

		public int getItemPosition(Object object) {
			return POSITION_NONE;
		}

		@Override
		public void startUpdate(ViewGroup arg0) {}
	}
	    
	@SuppressLint("NewApi") 
	public static class AdFragment extends Fragment {
		
		public AdFragment() {
			super();
        }
		
		@Override
		public View onCreateView(LayoutInflater inflater, ViewGroup container,
		                         Bundle savedInstanceState) {
		    return inflater.inflate(R.layout.fragment_ad, container, false);
		}
		
		private void removeViewFromSuperView(View view) {
			if (view == null) {
				return;
			}
			
			ViewParent parent = view.getParent();
			
			if (parent instanceof ViewGroup) {
				((ViewGroup)parent).removeView(view);
			}		
		}
		
		private void requestAds() {
			View view = getView();
			if(view == null) {
				return;
			}
			
			AdView adView = (AdView) view.findViewById(R.id.adView);
			if (adView == null) {
				return;
			}
			
		    AdRequest adRequest = new AdRequest.Builder().build();		    
		    adView.loadAd(adRequest);
		    adView.setAdListener(new AdListener() {
		    	@Override
		    	public void onAdFailedToLoad(int errorCode) {		    	
		    		super.onAdFailedToLoad(errorCode);
		    		Activity activity = getActivity();
		    		if (activity == null) {
						return;
					}
		    		
		    		View adView = ((MainActivity)activity).mAdFragmentView;
		    		if (adView != null) {
						removeViewFromSuperView(adView);
					}
		    		
		    		new Handler().postDelayed(new Runnable() {
						
						@Override
						public void run() {
							requestAds();
							
						}
					}, 3000);
		    	}
		    	
		    	@Override
		    	public void onAdLoaded() {		    	
		    		super.onAdLoaded();
		    		
		    		Activity activity = getActivity();
		    		if (activity == null) {
						return;
					}
		    		
		    		View adView = ((MainActivity)activity).mAdFragmentView;
		    		if (adView == null) {
						return;
					}
		    		
		    		if (adView.getParent() == null) {
		    			ViewGroup parentGroup = (ViewGroup)((ViewGroup)getActivity().findViewById(android.R.id.content)).getChildAt(0);
		    			if (parentGroup != null) {
							parentGroup.addView(adView);
						}						
					}
		    	}
			});
		}
		
		@Override
		public void onActivityCreated(Bundle bundle) {
		    super.onActivityCreated(bundle);
		    requestAds();
		}
	}
}
